package com.leesche.zcsp.node.web.controller.web.v3.place;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubPlace;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.PubPlaceService;
import com.leesche.zcsp.node.web.service.impl.data.read.InfoDeviceDto;
import com.leesche.zcsp.node.web.service.impl.data.read.PubPlaceDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDeviceCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubPlaceCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by kaider on 2017/2/22.
 */
@Controller
@RequestMapping("/v3/place")
public class WebPlaceV3Controller extends WebAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(WebPlaceV3Controller.class);

    private static final String SHOW_VIEW = "web/v3/place/showView";

    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private NetService netService;

    @RequestMapping(value = "/showView", method = RequestMethod.GET)
    public String showView(
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            Model model
    ) {
        getPlaces(placeCondition,model);
        getDevices(deviceCondition,model);
        model.addAttribute("cur",1);
        return SHOW_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/showDeviceList", method = RequestMethod.POST)
    public Map<String,Object> showDeviceList(
            int index,
            QueryPubDeviceCondition condition
    ){
        try {
            Long adminId = getAdminId();
            condition.setAdminId(adminId);
            if(condition.getPage()==-10){
                condition.setPage(1);
            }
            PagingResult<InfoDeviceDto> scrollResult = deviceService.selectDeviceListByPage(condition);

            //在线设备
            List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
            //离线设备
            List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
            //禁用设备
            List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
            //故障设备
            List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();
            if(scrollResult.getRows().size()>0){
                Map<String,String> onlineTemp = netService.isOnlineBatch(getDeviceNames(scrollResult.getRows()));
                for(InfoDeviceDto dto : scrollResult.getRows()) {
                    if (onlineTemp.get(dto.getImme()) != null && onlineTemp.get(dto.getImme()).equalsIgnoreCase("ONLINE")) {
                        dto.setIsOnline(1);
                    } else {
                        dto.setIsOnline(2);
                    }
                    if (dto.getIsOnline().equals(1) && dto.getState().equals(2)) {
                        disabled.add(dto);
                    } else if (dto.getIsOnline().equals(1)) {
                        online.add(dto);
                    } else if (dto.getIsOnline().equals(2)) {
                        offline.add(dto);
                    } else {
                        fault.add(dto);
                    }
                }
            }

            List<InfoDeviceDto> records = new ArrayList<InfoDeviceDto>();
            switch (index){
                case 0:
                    records = online;
                    break;
                case 1:
                    records = offline;
                    break;
                case 2:
                    records = disabled;
                    break;
                case 3:
                    records = fault;
                    break;
                default:
                    break;
            }
            scrollResult.setRows(records);

            return WebResult.success().put("scrollResult",scrollResult).toMap();

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 某个场地设备列表
     * @param placeId
     * @param placeCondition
     * @param deviceCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/{placeId}/placeView", method = RequestMethod.GET)
    public String showPlaceView(
            @PathVariable("placeId") Long placeId,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            Model model
    ) {
        getPlaces(placeCondition,model);
        getDevices(deviceCondition,model);
        PubPlaceDto dto = placeService.findByCondition(placeCondition);
        model.addAttribute("placeDto",dto);
        model.addAttribute("placeId",placeId);
        model.addAttribute("view",2);
        model.addAttribute("cur",1);
        return SHOW_VIEW;
    }

    /**
     * 添加场地
     * @param placeName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addPlace", method = RequestMethod.POST)
    public Map<String,Object> addPlace(
            String placeName
    ){
        try {
            Long adminId = getAdminId();
            PubPlace place = new PubPlace();
            place.setAdminid(adminId);
            place.setAddress(placeName);
            place.setState(1);
            place.setCreatetime(new Date());
            place.setUpdatetime(new Date());
            placeService.insert(place);
            Long placeId = place.getPlaceid();
            return WebResult.success().put("place",placeId).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 更改场地名称
     * @param placeId
     * @param placeName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{placeId}/editPlaceName", method = RequestMethod.POST)
    public Map<String,Object> editPlaceName(
            @PathVariable("placeId") Long placeId,
            String placeName
    ){
        try {
            PubPlace oldPlace = placeService.selectByPrimaryKey(placeId);
            oldPlace.setAddress(placeName);
            placeService.updateByPrimaryKeySelective(oldPlace);
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 获取场地信息
     * @param condition
     * @param model
     * @return
     */
    private Model getPlaces(
            QueryPubPlaceCondition condition,
            Model model
    ){
        Long adminId = getAdminId();
        condition.setAdminId(adminId);
        List<PubPlaceDto> list = placeService.findPubPlaceList(condition);
        model.addAttribute("placeList",list);
        return model;
    }

    /**
     * 获取设备信息
     * @param condition
     * @param model
     * @return
     */
    private Model getDevices(
            QueryPubDeviceCondition condition,
            Model model
    ){
        Long adminId = getAdminId();
        condition.setAdminId(adminId);
        List<InfoDeviceDto> list = deviceService.findDeviceList(condition);
        //在线设备
        List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
        //离线设备
        List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
        //禁用设备
        List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
        //故障设备
        List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();
        if(list.size()>0){
            Map<String,String> onlineTemp = netService.isOnlineBatch(getDeviceNames(list));
            for(InfoDeviceDto dto : list) {
                if (onlineTemp.get(dto.getImme()) != null && onlineTemp.get(dto.getImme()).equalsIgnoreCase("ONLINE")) {
                    dto.setIsOnline(1);
                } else {
                    dto.setIsOnline(2);
                }
                if (dto.getIsOnline().equals(1) && dto.getState().equals(2)) {
                    disabled.add(dto);
                } else if (dto.getIsOnline().equals(1)) {
                    online.add(dto);
                } else if (dto.getIsOnline().equals(2)) {
                    offline.add(dto);
                } else {
                    fault.add(dto);
                }
            }
        }
        model.addAttribute("online", online);
        model.addAttribute("offline", offline);
        model.addAttribute("disabled", disabled);
        model.addAttribute("fault", fault);
        return model;
    }

    private List<String> getDeviceNames(List<InfoDeviceDto> lists) {
        List<String> deviceNames = new ArrayList<String>();
        if (lists != null) {
            for (InfoDeviceDto infoDeviceDto : lists) {
                deviceNames.add(infoDeviceDto.getImme());
            }
        }
        return deviceNames;
    }

}
